package org.qloudgen.borg.task;

import org.qloudgen.borg.beans.CacheBean;
import org.qloudgen.borg.beans.Cluster;
import org.qloudgen.borg.beans.UserBean;
import org.qloudgen.borg.messaging.message.TaskMessage;
import org.qloudgen.borg.metadb.DefaultImpl;

public final class TaskRules {

	/*
	 * check if task can be executed on an assigned cluster.
	 */
	public static boolean isExecuted(TaskMessage message){
		
		// check quota
		if (checkUserQuota(message.getUserNo()) && checkClusterQuota(message.getClusterID())) return true;
		
		return false;
	}
	
	/*
	 * check if user task can be executed at same time
	 */
	private static boolean checkUserQuota(String userNo){
		
		// get user task number 
		UserBean user = DefaultImpl.getUserInfo(userNo);
		
		// get running tasks by userNo
		int taskNumber = DefaultImpl.getUserRunningTaskNumber(userNo);
		
		// cluster can not execute user's task number more than the allocated number at same time
		if (taskNumber < user.getTaskNumber()) return true;
		
		return false;
		
	}
	
	/*
	 *  check if cluster can execute more tasks
	 */
	private static boolean checkClusterQuota(String clusterID){
		
		// get cluster task number 
		Cluster cluster = DefaultImpl.getClusterInfo(clusterID);
		
		// get running tasks by clusterID
		int taskNumber = DefaultImpl.getClusterRunningTaskNumber(clusterID);
		
		// cluster has no resources to execute task or cluster has no resource control
		if (taskNumber < cluster.getMaxTasks() || cluster.getMaxTasks() == 0) return true;
		
		return false;
		
	}
	
	/*
	 * check if the task can be submitted
	 */
	public static boolean isSubmit(CacheBean cache){
		
		if (!cache.isReload()) return true;
		
		// get task counts from metadb by func_no,dn_no,cluster_id
		int taskNumber = DefaultImpl.getClusterFuncDSTaskNumber(cache);
		
		if (taskNumber > 0 ) return false;
		
		return true;
	}
	
	/*
	 * check if reload task exists
	 */
	public static boolean isExistsReloadTask(CacheBean cache) {
		
		// get task counts from metadb by func_no,dn_no,cluster_id
		int taskNumber = DefaultImpl.getClusterFuncDSReloadTaskNumber(cache);
		
		if (taskNumber > 0 ) return true;
		
		return false;
	}
}
